package org.siam.impl.schemas.properties {
	
	import org.siam.core.ISiamManager;
	import org.siam.core.data.IDataManager;
	import org.siam.core.schemas.properties.ISchemaProperty;
	import org.siam.utils.RuntimeError;
	import org.siam.utils.StringUtils;
	
	public class SchemaPropertyXMLHandler {
		
		
		public static function read(input:XML, schemaId:String, siam:ISiamManager):ISchemaProperty {
			var instance:SchemaProperty = new SchemaProperty();
			var propertyId:String = input["@id"];
			instance._id = propertyId;
			
			for each (var attributeXML:XML in input.attributes()) {
				var key:String = attributeXML.name();
				var value:String = attributeXML.toString();
				switch (key) {
					case "id": break;
					case "formatter": 
						instance._formatterId = value;
						process(value, siam.formatters, key, propertyId, schemaId); 
						break;
					case "renderer": 
						instance._rendererId = value;
						process(value, siam.renderers, key, propertyId, schemaId); 
					break;
					case "editor": 
						instance._editorId = value; 
						process(value, siam.editors, key, propertyId, schemaId);
						break;
					case "validator": 
						instance._validatorId = value;
						process(value, siam.validators, key, propertyId, schemaId); 
						break;
					default: 
						instance.registerMetadata(key, value); 
						break;
				}
			}
			return instance;
		}
	
		private static function process(id:String, manager:IDataManager, type:String, propertyId:String, schemaId:String):void {
			if (StringUtils.isEmpty(id) || (id && !manager.has(id))) {
				throw new RuntimeError("Unknown {0} '{1}' for property '{2}' under schema '{3}'",
										type, id, propertyId, schemaId);
			}
		}
	}
}